<template>
  <view class="phoneLogin">
    <view class="content">
      <image src="../../static/YinrunLogo.png" mode="scaleToFill" />
      <view class="box">
        <!-- 自定义切换按钮 -->
        <view class="switch-tabs">
          <view
            class="tab-item"
            :class="{ active: current === 0 }"
            @click="setCurrent(0)"
          >
            手机号登录
          </view>
          <view
            class="tab-item"
            :class="{ active: current === 1 }"
            @click="setCurrent(1)"
          >
            用户名登录
          </view>
        </view>

        <!-- 手机号登录 -->
        <view class="formAction">
          <view class="phone" v-if="current === 0">
            <view class="ipt">
              <text style="color: aliceblue; padding-left: 32rpx">手机号码</text>
              <text class="error-tip" v-if="errors.phone">{{ errors.phone }}</text>
              <input
                type="number"
                placeholder="请输入手机号"
                placeholder-style="color:#666"
                v-model="params.phone"
                :maxlength="11"
              />
            </view>
            <view class="ipt">
              <text style="color: aliceblue; padding-left: 32rpx">验证码</text>
              <text class="error-tip" v-if="errors.security">{{ errors.security }}</text>
              <view class="security">
                <input
                  type="number"
                  placeholder="请输入验证码"
                  placeholder-style="color:#666"
                  v-model="params.security"
                  :maxlength="6"
                  :minlength="4"
                  :disabled="!isCodeSent" 
                />
                <view
                  class="code"
                  @click="getCode"
                  :class="{ disabled: !isPhoneValid || isDisabled }"
                  :style="{
                    color: isPhoneValid && !isDisabled ? '#1A195A' : '#ccc',
                  }"
                >| {{ buttonText }}</view>
              </view>
            </view>
          </view>

          <!-- 用户名登录 -->
          <view class="username" v-else>
            <view class="ipt">
              <text style="color: aliceblue; padding-left: 32rpx">用户名</text>
              <text class="error-tip" v-if="errors.username">{{ errors.username }}</text>
              <input
                type="text"
                placeholder="请输入用户名"
                placeholder-style="color:#666"
                v-model="params.username"
                :maxlength="11"
              />
            </view>
            <view class="ipt">
              <text style="color: aliceblue; padding-left: 32rpx">密码</text>
              <text class="error-tip" v-if="errors.loginPassword">{{ errors.loginPassword }}</text>
              <input
                password
                type="text"
                placeholder="请输入密码"
                placeholder-style="color:#666"
                v-model="params.password"
              />
            </view>
          </view>

          <!-- 协议 -->
          <view class="agreement">
            <wd-checkbox
              v-model="agree"
              @toggle="handleSelected"
              checked-color="blue"
            />
            <text class="agree-text">我已阅读并接受《隐私政策》和《服务协议》</text>
          </view>

          <!-- 登录按钮 -->
          <button class="login" @click="handleLogin">登录</button>

          <!-- 注册/忘记密码 -->
          <view class="footer">
            <view class="register" @click="handleRegister">免费注册</view>
            <view class="forget" @click="handleReset">忘记密码?</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { apiSendCode, apiAccountLogin, apiAccountList } from "../../api/login";
import { Local } from "../../utils/storage";

// 当前登录模式
const current = ref(0);
const setCurrent = (index) => {
  current.value = index;
};

// 是否同意协议
const agree = ref(false);
const handleSelected = () => {
  agree.value = !agree.value;
};

// 表单数据
const params = ref({
  phone: "",
  security: "",
  username: "",
  password: "",
});

// 错误信息
const errors = ref({});

// 验证码是否已发送（控制输入框是否可用）
const isCodeSent = ref(false);

// 验证码发送时间戳（用于判断是否过期）
let codeSentTime = null;

//重置密码
const handleReset = () => {
  // uni.navigateTo({
  //   url: "/subPackage/login/resetPassword",
  // });
  uni.showToast({
    title: "请手机号登录",
    icon: "none",
  });
};
//注册
const handleRegister = () => {
  uni.navigateTo({
    url: "/subPackage/login/userRegister",
  });
};

// 手机号格式校验
const isPhoneValid = computed(() => {
  const phone = params.value.phone;
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
});

// 验证码倒计时
const isDisabled = ref(false);
const buttonText = ref("获取验证码");
let timer = null;

// 获取验证码
const getCode = async () => {
  if (!isPhoneValid.value || isDisabled.value) return;

  const phone = params.value.phone;

  const res = await apiSendCode({ phone });
  if (res.code !== 200) {
    uni.showToast({ title: res.message || "发送失败", icon: "none" });
    return;
  }

  // ✅ 验证码发送成功后，允许输入
  isCodeSent.value = true;
  codeSentTime = Date.now(); // 记录发送时间

  uni.showToast({ title: "验证码已发送", icon: "none" });

  // 开始倒计时
  isDisabled.value = true;
  let count = 60;
  timer = setInterval(() => {
    if (count > 0) {
      buttonText.value = `${count}秒重新获取`;
      count--;
    } else {
      clearInterval(timer);
      timer = null;
      buttonText.value = "获取验证码";
      isDisabled.value = false;
    }
  }, 1000);
};

// 校验验证码是否过期（60秒内有效）
const isCodeExpired = () => {
  if (!codeSentTime) return true;
  return Date.now() - codeSentTime > 60000; // 超过60秒
};

// 手机号登录校验
const validateFormPhone = () => {
  errors.value = {};
  let isValid = true;

  const phone = params.value.phone;
  const security = params.value.security.trim();

  // 手机号校验
  if (!phone) {
    errors.value.phone = "请输入手机号码";
    isValid = false;
  } else if (!isPhoneValid.value) {
    errors.value.phone = "请输入正确的手机号";
    isValid = false;
  }

  // 验证码校验
  if (!security) {
    errors.value.security = "请输入验证码";
    isValid = false;
  } else if (security.length < 4) {
    // 输入了但不足4位
    errors.value.security = "验证码长度不能小于4位";
    isValid = false;
  } else if (![4, 6].includes(security.length)) {
    // 不是4位或6位
    errors.value.security = "验证码必须为4位或6位";
    isValid = false;
  } else if (!isCodeSent.value) {
    errors.value.security = "请先获取验证码";
    isValid = false;
  } else if (isCodeExpired()) {
    errors.value.security = "验证码已过期，请重新获取";
    isValid = false;
  }

  return isValid;
};
// 账号登录校验
const validateFormAccount = () => {
  errors.value = {};
  let isValid = true;

  const username = params.value.username.trim();
  const password = params.value.password.trim();

  if (!username) {
    errors.value.username = "请输入用户名";
    isValid = false;
  }

  if (!password) {
    errors.value.password = "请输入登录密码";
    isValid = false;
  }

  return isValid;
};

// 登录处理
// 登录处理
const handleLogin = async () => {
  if (!agree.value) {
    uni.showToast({ title: "请勾选协议", icon: "none" });
    return;
  }

  if (current.value === 0) {
    // 手机号登录
    if (!validateFormPhone()) return;

    // 调用获取用户列表接口
    const phoneRes = await apiAccountList({
      verificationCode: params.value.security,
      phone: params.value.phone,
    });

    // 接口请求失败（网络错误、参数错误等）
    if (phoneRes.code !== 200) {
      uni.showToast({ title: phoneRes.message || "登录失败", icon: "none" });
      return;
    }

    // ✅ 接口成功，但用户列表为空 → 手机号未注册
    const userList = phoneRes.data.userList;
    if (!userList || userList.length === 0) {
      uni.showModal({
        title: "提示",
        content: "该手机号尚未注册，是否前往注册？",
        confirmColor: "#5756b3",
        success: function (res) {
          if (res.confirm) {
            handleRegister(); // 跳转注册
          }
        },
      });
      return;
    }

    // ✅ 用户存在，保存数据并跳转多账号选择页
    Local.set("userInfo", userList);
    uni.navigateTo({
      url: `/subPackage/login/multipleAccount?phone=${params.value.phone}`,
    });

  } else {
    // 账号登录（保持不变）
    if (!validateFormAccount()) return;

    const loginRes = await apiAccountLogin({
      username: params.value.username,
      password: params.value.password,
    });

    if (loginRes.code === 200) {
      uni.showToast({ title: "登录成功", icon: "none" });
      Local.set('token', loginRes.data.token)
      Local.set('userItem', loginRes.data.user)
      setTimeout(() => {
        uni.navigateTo({ url: "/pages/index/index" });
      }, 500);
    } else {
      uni.showToast({ title: loginRes.msg || "登录失败", icon: "none" });
    }
  }
};
</script>

<style lang="scss" scoped>
/* 保持原样式不变 */
.phoneLogin {
  background-color: #959bfe;
  height: 100vh;
  width: 100vw;
  overflow: hidden;

  .content {
    height: calc(100% - 70rpx);
    width: 100%;
    padding-top: 150rpx;

    image {
      width: 200rpx;
      height: 200rpx;
      margin-left: 285rpx;
      border-radius: 20rpx;
      margin-bottom: 100rpx;
    }

    .box {
      height: 750rpx;
      background-color: #a0c0fe;
      margin: 0 40rpx;
      border-radius: 40rpx;

      .switch-tabs {
        display: flex;
        background-color: transparent;
        border-radius: 40rpx 40rpx 0 0;
        overflow: hidden;
        font-size: 32rpx;
        border-bottom: none;

        .tab-item {
          flex: 1;
          text-align: center;
          padding: 30rpx 0;
          color: #666;
          transition: all 0.3s ease;
          position: relative;
          border: none;

          &.active {
            background: #b8c2fe;
            color: #1a195a;
            font-weight: bold;
          }

          &:not(.active) {
            background: #cfdafe;
            color: #a5b7fe;
          }
        }
      }

      .security {
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;

        input {
          margin-top: 10rpx;
          width: calc(100% - 350rpx);
          height: 80rpx;
          background-color: #fff;
          border-radius: 40rpx;
          padding-left: 50rpx;
          padding-right: 300rpx;
        }

        .code {
          position: absolute;
          left: 330rpx;
          top: 40rpx;
          right: 0;
        }
      }

      .formAction {
        padding: 0 30rpx;

        .ipt {
          margin-top: 40rpx;
          padding: 0 40rpx;

          input {
            margin-top: 20rpx;
            width: calc(100% - 300rpx);
            height: 80rpx;
            background-color: #fff;
            border-radius: 40rpx;
            padding-left: 50rpx;
            padding-right: 250rpx;
          }

          .error-tip {
            font-size: 24rpx;
            color: #e74c3c;
            margin-top: 8rpx;
            padding-left: 40rpx;
            height: 36rpx;
            line-height: 36rpx;
            margin-left: 100rpx;
          }
        }

        .agreement {
          display: flex;
          align-items: center;
          margin-bottom: 24rpx;
          font-size: 24rpx;
          color: #666;
          padding-left: 40rpx;
          margin-top: 40rpx;

          .agree-text {
            margin-left: 10rpx;
            color: #1a195a;
            font-size: 25rpx;
          }
        }

        .login {
          margin-top: 40rpx;
          background-color: #5756b3;
          color: #fff;
          border-radius: 40rpx;
          height: 90rpx;
          width: 550rpx;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .footer {
          margin-top: 40rpx;
          color: #6469c0;
          font-size: 25rpx;
          margin-right: 20rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }
  }
}
</style>